package com.taichuan.keysupport.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.taichuan.keysupport.Key;

/**
 * Created by OISNY on 2016/8/19.
 */
public class KSEditText extends EditText {
    private static final String TAG = KSEditText.class.getSimpleName();

    public KSEditText(Context context) {
        super(context);
        init();
    }

    public KSEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public KSEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setOnFocusChangeListener(mFocusChangeListener);
        setOnKeyListener(mKeyListener);
    }

    public OnFocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                String str = getText().toString();
                setSelection(str.length());
            }
        }
    };

    public OnKeyListener mKeyListener = new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.i(TAG, "onKey: 接收到点击事件 keyCode:  " + keyCode + "  event:  " + event.toString());
            if (Key.Convert.KEYCODE_XING == keyCode || Key.Convert.KEYCODE_DEL == keyCode) {
                if (getText().toString().length() > 0) {
                    // 退格
                    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN,
                            KeyEvent.KEYCODE_DEL);
                    dispatchKeyEvent(keyEvent);
                    return true;
                }
            } else if (Key.Convert.KEYCODE_LONG_0 == keyCode) {
                setText(getText().toString() + ".");
                setSelection(getText().toString().length());
                return true;
            }
            return false;
        }
    };

}
